<?php

require_once 'dbvars.php';

// Connect to server and select databse.
$con = new mysqli("$host", "$username", "$password", "$db_name");
if ($con->connect_error)
{
    die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}

// username and password sent from form 
$username = $_POST['uname']; 
$password = $_POST['pass'];
$mail= $_POST['mail'];

// To protect MySQL injection (more detail about MySQL injection)
//$username = stripslashes($username);
//$password = stripslashes($password);
//$mail = stripslashes($mail);
$username = $con->real_escape_string($username);
$password = $con->real_escape_string($password);
$mail = $con->real_escape_string($mail);
$sql = "SELECT id, username, AES_DECRYPT(password, '$mail') as password, isadmin FROM $user_tbl_name WHERE username='$username' and password=AES_ENCRYPT('$password', '$mail')";
$result = $con->query($sql);

// Mysql_num_row is counting table row
$count = $result->num_rows;

// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
    session_start();
    $_SESSION['username']= $username;
    $_SESSION['password']= $password;
    $row = $result->fetch_row();
    $_SESSION['uid'] = $row[0];
    $_SESSION['isadmin'] = ($row[3]) ? 'yes' : 'no';

    echo '<script>
              url = window.opener.location;
              window.opener.location = url;
              window.close();
          </script>';
}
else {
    echo '<script>
              alert("Грешно потребителско име или парола!");
              url = window.opener.location;
              window.opener.location = url;
              window.close();
          </script>';
}
?>
